package com.zheng.study.base.service.memcached;

import com.thimbleware.jmemcached.CacheImpl;
import com.thimbleware.jmemcached.Key;
import com.thimbleware.jmemcached.LocalCacheElement;
import com.thimbleware.jmemcached.MemCacheDaemon;
import com.thimbleware.jmemcached.storage.CacheStorage;
import com.thimbleware.jmemcached.storage.hash.ConcurrentLinkedHashMap;
import net.spy.memcached.AddrUtil;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

import java.net.InetSocketAddress;

/**
 * newFile
 * ============================================================================
 * author : dzw
 * createDate:  2018/8/21 。
 * ============================================================================
 */
public class MemcachedSimulator implements InitializingBean, DisposableBean {
	private MemCacheDaemon<LocalCacheElement> jmemcached;
	private String serverUrl = "localhost:11212";
	private int maxItems = 102400;
	private long maxBytes = 209715200L;

	public MemcachedSimulator() {
	}

	public void afterPropertiesSet() throws Exception {
		this.jmemcached = new MemCacheDaemon();
		CacheStorage<Key, LocalCacheElement> storage = ConcurrentLinkedHashMap.create(ConcurrentLinkedHashMap.EvictionPolicy.FIFO, this.maxItems, this.maxBytes);
		this.jmemcached.setCache(new CacheImpl(storage));
		this.jmemcached.setAddr((InetSocketAddress) AddrUtil.getAddresses(this.serverUrl).get(0));
		this.jmemcached.start();
	}

	public void destroy() throws Exception {
		this.jmemcached.stop();
	}

	public void setServerUrl(String serverUrl) {
		this.serverUrl = serverUrl;
	}

	public void setMaxItems(int maxItems) {
		this.maxItems = maxItems;
	}

	public void setMaxBytes(long maxBytes) {
		this.maxBytes = maxBytes;
	}
}
